﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using TruckScale.Helpers;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.Models
{
  public class RoleModel
  {
    public int? RoleId { get; set; }
    public string RoleName { get; set; }
    public string RolePermission { get; set; }
    public bool IsValid { get; set; } = true;
    public static List<RoleModel> SelectAllRole()
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = "select * from role;";
          IEnumerable<RoleModel> output = cnn.Query<RoleModel>(sql);
          return output.ToList();
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return null;
        }
      }
    }
    public static List<RoleModel> SelectActiveRole()
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = "select * from role where is_valid = 1;";
          IEnumerable<RoleModel> output = cnn.Query<RoleModel>(sql);
          return output.ToList();
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return null;
        }
      }
    }
    public static RoleModel SelectUniqueRoleByName(RoleModel role)
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = $"select * from role where role_name = '{role.RoleName}' and role_id != '{role.RoleId}';";
          RoleModel output = cnn.QueryFirstOrDefault<RoleModel>(sql);
          return output;
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return new RoleModel();
        }
      }
    }
    public static int InsertRole(RoleModel role)
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = "insert into role (role_name, role_permission) values (@RoleName, @RolePermission);";
          return cnn.Execute(sql, role);
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return -1;
        }
      }
    }
    public static int UpdateRole(RoleModel role)
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = "update role set role_name = @RoleName, role_permission = @RolePermission, is_valid = @IsValid WHERE role_id = @RoleId;";
          return cnn.Execute(sql, role);
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return -1;
        }
      }
    }
  }
}
